package excelBase;

import java.io.File;
import java.util.ArrayList;

import main.ErrorException;
import main.ErrorHandler;
import main.WarningHandler;
import script.Script;
import define.Common;
import define.Config;
import define.ErrorDefine;
import define.ExcelType;
import define.WarningDefine;

public class ExcelData 
{
	private static ArrayList<ExcelFile> m_excelFiles = new ArrayList<>();
	
	public static ExcelFile readExcel(String fileName) throws ErrorException
	{
		String name = Common.getWithoutExtendName(fileName);
		for(ExcelFile file: m_excelFiles)
		{
			if(file.getName().compareTo(name) == 0)
			{
				new WarningHandler(WarningDefine.E_FILE_WITH_SAME_NAME_WARNING, name, Config.NO_POSITION).showWarning();
			}
		}
		ExcelFile temp = new ExcelFile(fileName);
		ErrorHandler.m_errorExcel = temp;
		temp.init();
		m_excelFiles.add(temp);
		return temp;
	}
	
	public static ExcelFile readExcel(File file) throws ErrorException
	{
		return readExcel(file.getAbsolutePath());
	}
	
	public static ExcelFile getExcelFile(String name, int position) throws ErrorException
	{
		for(ExcelFile temp: m_excelFiles)
		{
			if(temp.getName().compareTo(name) == 0)
			{
				return temp;
			}
		}
		throw new ErrorException(ErrorDefine.E_NO_EXCEL_FILE_ERROR, name, position);
	}
	
	public static void complieScript() throws ErrorException
	{
		for(ExcelFile temp: m_excelFiles)
		{
			temp.compileScript();
		}
	}
	
	public static void output() throws ErrorException
	{
		for(ExcelFile temp: m_excelFiles)
		{
			temp.output();
		}
	}
	
	public static Script getScript(String name) throws ErrorException
	{
		Script script = null;
		for(ExcelFile temp: m_excelFiles)
		{
			script = temp.getScript(name);
			if(script != null)
			{
				return script;
			}
		}
		return null;
	}
	
	public static void clearData()
	{
		m_excelFiles.clear();
	}
	
	public static ArrayList<Sheet> getSheetSetByExcelType(ExcelType type, int position) throws ErrorException
	{
		ArrayList<Sheet> m_outList = new ArrayList<>();
		for(ExcelFile file: m_excelFiles)
		{
			for(int i = 0, max = file.getChildNumber(); i < max; ++i)
			{
				Sheet sheet = (Sheet)file.getChild(i, position);
				if(sheet.getExcelType() == type)
				{
					m_outList.add(sheet);
				}
			}
		}
		return m_outList;
	}
}
